# code:utf8
import logging
from zc_core.model.items import ItemData, Sku, Order
from zc_core.util.common import parse_number, parse_time
from zc_core.util.sku_id_parser import convert_id2code
from pyquery import PyQuery

from plap_deli.items import PlapOrder
from plap_deli.matcher import *

logger = logging.getLogger('rule')


# 解析sku列表页数
def parse_sku_page(response):
    jpy = PyQuery(response.text)
    last_link = jpy('div.pagination li.last a').attr('href')
    return match_sku_total_page(last_link)


# 解析sku列表
def parse_sku(response):
    skus = list()
    jpy = PyQuery(response.text)
    lis = jpy('div.productlist ul li')
    if lis and lis.size() > 1:
        for li in lis.items():
            sku_link = li('div.product_name a')
            url = sku_link.attr('href')
            sku_name = sku_link.text().strip()
            sale_price = li('div.product_price').text().strip().strip('¥')
            mark_price = li('div.product_market_price').text().strip().strip('市场参考价：¥')
            photo_link = li('div.product_photo img')
            sku_img = 'http://mall.plap.cn' + photo_link.attr('src')
            sku = Sku()
            link_id = match_product_id(url)
            sku['skuId'] = link_id
            sku['skuName'] = sku_name
            sku['skuImg'] = sku_img
            sku['salePrice'] = parse_number(sale_price)
            sku['originPrice'] = parse_number(mark_price)
            skus.append(sku)

    return skus


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    sku = meta.get('sku')
    item = ItemData()
    item.update(sku)

    jpy = PyQuery(response.text)
    code_div = jpy('div.goods_price div.attribute > div.dt:contains("商品编号：") + div.gs')
    if code_div:
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        sp_sku = code_div('span#psku_tag')
        if sp_sku and sp_sku.text():
            sp_sku_id = sp_sku.text().replace('(', '').replace(')', '').strip()
            item['supplierSkuId'] = sp_sku_id
            sp_sku_code = convert_id2code('deli', sp_sku_id)
            item['supplierSkuCode'] = sp_sku_code
        sp_sku.remove()
        material_code = code_div.text().strip()
        if material_code:
            item['materialCode'] = material_code

    return item


def parse_total_order_page(response):
    jpy = PyQuery(response.text)
    last_link = jpy('div.pagination li.last a').attr('href')
    return match_total_order_page(last_link)


def parse_order_list(response):
    order_list = list()
    jpy = PyQuery(response.text)
    trans_divs = jpy('div.myorder_right div.transaction')
    for trans_div in trans_divs.items():
        order_time_span = trans_div('span')
        order_time = parse_time(order_time_span.text().strip().replace('下单时间：', ''))
        order_time_span.remove()
        order_id = trans_div.text().strip().replace('订单编号：', '')

        goods_div = trans_div.next()
        divs = goods_div('div.w110')
        user_id = divs.eq(0).text().strip()
        order_type = divs.eq(1).text().strip()
        total_price = parse_number(divs.eq(3).text().strip())
        status = divs.eq(4).text().strip()

        order = PlapOrder()
        order['id'] = order_id
        order['orderUser'] = user_id
        order['orderTime'] = order_time
        order['totalPrice'] = total_price
        order['status'] = status
        order['tradeType'] = order_type
        order_list.append(order)

    return order_list


def parse_order_detail(response):
    meta = response.meta
    order_id = meta.get('orderId')
    order_time = meta.get('orderTime')
    order = PlapOrder()
    order['id'] = order_id
    order['orderTime'] = order_time

    jpy = PyQuery(response.text)
    main_order_spans = jpy('h1:contains("订单详情") + div.reminder span')
    if main_order_spans.size() == 5:
        # 正常订单
        # 验收单号
        order['receiptCode'] = main_order_spans.eq(2)('b').text()
        # 客户类型
        order['clientType'] = main_order_spans.eq(4)('b').text()
    else:
        # 取消订单
        # 验收单号
        order['cancelReason'] = match_reason(main_order_spans.eq(1)('b').text())
        # 客户类型
        order['clientType'] = main_order_spans.eq(3)('b').text()

    # 供应商订单编号
    sp_p = jpy('h2:contains("供应商信息") + div.reminder > p:contains("订单编号：")')
    order['spOrderCode'] = sp_p.text().strip().replace('（订单编号：', '').replace('）', '')
    # 收货信息
    addr_p = jpy('h2:contains("订单信息") + div.reminder > p:contains("收货信息：")')
    order['orderAddr'] = addr_p.text().strip().replace('收货信息：', '')

    item_list = list()
    order['itemList'] = item_list
    trs = jpy('h2:contains("商品信息") + table.Ptable tr')
    for idx, tr in enumerate(trs.items()):
        if idx == trs.length - 1:
            continue

        tds = tr('td')
        order_item = dict()
        sku_link = tds.eq(0)('a').eq(0)
        url = sku_link.attr('href')
        order_item['skuId'] = url.replace('/products/', '')
        order_item['skuName'] = sku_link.attr('title')
        order_item['url'] = 'http://mall.plap.cn{}'.format(url)
        order_item['count'] = parse_number(tds.eq(1).text().strip())
        order_item['amount'] = parse_number(tds.eq(5).text().strip())

        item_list.append(order_item)

    return order